from django import http

from apps.news.models import News
from utils import constants


def get_click_list():
    news_list = None
    try:
        # 查询数据按点击量降序，只查询前10条
        news_list = News.objects.order_by('-clicks')[:10]
    except Exception as e:
        return http.HttpResponseBadRequest('查询点击排行数据失败')

    click_news_list = []
    # 遍历新闻列表，把里面的新闻对象转换为字典
    for news in news_list if news_list else []:
        click_news_list.append({
            "id": news.id,
            "title": news.title,
            "source": news.source,
            "digest": news.digest,
            "create_time": news.create_time.strftime("%Y-%m-%d %H:%M:%S"),
            "index_image_url": news.index_image_url,
            "clicks": news.clicks,
        })
    return click_news_list


def get_user_info(request):
    user_info = None
    if request.user.is_authenticated():
        user_info = {
            "id": request.user.id,
            "username": request.user.username,
            "avatar_url": constants.QINIU_DOMIN_PREFIX + request.user.avatar_url if request.user.avatar_url else "",
            "mobile": request.user.mobile,
            "gender": 'WOMAN' if request.user.gender == 1 else "MAN",
            "signature": request.user.signature if request.user.signature else "",
            "followers_count": request.user.followers.count(),
            "news_count": request.user.news_list.count()
        }
    return user_info
